package logic

import (
	"context"
	"edu/models/cache"
	"edu/models/mysql"
	"encoding/json"
	"fmt"
	"time"

	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ContentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewContentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ContentListLogic {
	return &ContentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ContentListLogic) ContentList(in *edurpc.ContentListRequest) (*edurpc.ContentListResponse, error) {
	var contents []mysql.ContentList
	key := fmt.Sprintf("content_list_%d%d", in.UserId, in.NovelId)
	cacheList, _ := cache.Rdb.Get(l.ctx, key).Result()
	if cacheList == "" {
		mysql.DB.Table("contents").
			Select("users.nick_name,novels.title,refer").
			Joins("LEFT JOIN users ON users.id = contents.user_id").
			Joins("LEFT JOIN novels on novels.id = contents.user_id").
			Where("contents.novel_id = ?", in.NovelId).
			Order("contents.created_at desc").Find(&contents)
		cacheJson, _ := json.Marshal(contents)
		cache.Rdb.Set(l.ctx, key, cacheJson, time.Minute*15)
	} else {
		json.Unmarshal([]byte(cacheList), &contents)
	}
	var contentList []*edurpc.ContentList
	for _, content := range contents {
		list := edurpc.ContentList{
			NickName: content.NickName,
			Title:    content.Title,
			Refer:    content.Refer,
		}
		contentList = append(contentList, &list)
	}
	return &edurpc.ContentListResponse{
		List: contentList,
	}, nil
}
